package com.qst.crop.controller;

import com.github.pagehelper.PageInfo;
import com.qst.crop.common.Result;
import com.qst.crop.common.StatusCode;
import com.qst.crop.entity.Expert;
import com.qst.crop.entity.Question;
import com.qst.crop.service.ExpertService;
import com.qst.crop.service.QuestionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author QST
 * @Description 问题模块
 * @Date 2021-08-24
 */
@RestController
@RequestMapping("/question")
@Tag(name = "问题模块接口")
@CrossOrigin
public class QuestionController {
    @Autowired
    private QuestionService questionService;
    @Autowired
    private ExpertService expertService;

    //根据ID查询询问情况
    @Operation(summary = "根据ID查询询问情况")
    @GetMapping("/selectId/{id}")
    public Result<Question> selectById(@PathVariable("id") Integer id) {
        Question question = questionService.queryById(id);
        return new Result<Question>(true, StatusCode.OK, "查询成功", question);
    }

    //添加询问情报
    @Operation(summary = "添加询问情报")
    @PostMapping("/add")
    public Result<String> add(@RequestBody Question question, BindingResult bindingResult) {
        //检查项目
        if (bindingResult.hasErrors()) {
            StringBuffer stringBuffer = new StringBuffer();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors) {
                stringBuffer.append(objectError.getDefaultMessage()).append("; ");
            }
            String s = stringBuffer.toString();
            System.out.println(s);
            return new Result<String>(false, StatusCode.ERROR, "添加失败",s);
        }
        
        // 获取当前登录用户信息并设置提问者
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails principal = (UserDetails) authentication.getPrincipal();
        String currentUsername = principal.getUsername();
        question.setQuestioner(currentUsername);
        
        questionService.insert(question);
        return new Result<String>(true, StatusCode.OK, "添加成功");
    }

    //根据id修改询问情报
    @Operation(summary = "根据id修改询问情报")
    @PutMapping("/update")
    public Result<String> update(@RequestBody Question question, BindingResult bindingResult) {
        //检查项目
        if (bindingResult.hasErrors()) {
            StringBuffer stringBuffer = new StringBuffer();
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors) {
                stringBuffer.append(objectError.getDefaultMessage()).append("; ");
            }
            String s = stringBuffer.toString();
            System.out.println(s);
            return new Result<String>(false, StatusCode.ERROR, "修改失败",s);
        }
        questionService.updateById(question.getId(), question);
        return new Result<String>(true, StatusCode.OK, "修改成功");
    }

    //根据id删除询问情报
    @Operation(summary = "根据id删除询问情报")
    @DeleteMapping("/delete/{id}")
    public Result<String> delete(@PathVariable("id") Integer id) {
        questionService.deleteById(id);
        return new Result<String>(true, StatusCode.OK, "删除成功");
    }

    //根据用户查询询问情况
    @Operation(summary = "根据用户查询询问情况")
    @GetMapping("/selectByKind/{kind}")
    public Result<List<Question>> selectByKind(@PathVariable("kind") String kind) {
        System.out.println("=== QuestionController.selectByKind 被调用 ===");
        System.out.println("传入的kind参数: " + kind);
        
        // 获取当前登录用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails principal = (UserDetails) authentication.getPrincipal();
        String currentUsername = principal.getUsername();
        
        System.out.println("当前登录用户: " + currentUsername);
        
        // 直接使用当前登录用户查询，忽略前端传递的参数
        System.out.println("开始查询用户问答记录...");
        List<Question> questions = questionService.selectByQuestioner(currentUsername);
        System.out.println("查询到的问答记录数量: " + (questions != null ? questions.size() : "null"));
        System.out.println("问答记录详情: " + questions);
        
        return new Result<List<Question>>(true, StatusCode.OK, "查询成功", questions);
    }
    
    //按条件分页条件查询所有问答情况
    @Operation(summary = "分页条件查询所有问答情况")
    @GetMapping("/findPageQues/{keys}/{pageNum}")
    public Result<PageInfo<Question>> findPageQues(@PathVariable("keys") String keys,@PathVariable Integer pageNum) {
            PageInfo<Question>  questionPageInfo = questionService.findPageQues(keys,pageNum);
        return new Result<PageInfo<Question>>(true, StatusCode.OK, "查询成功", questionPageInfo);
    }
    
    //分页查询所有问答情况
    @Operation(summary = "分页查询所有问答情况")
    @GetMapping("/findAllQues/{pageNum}")
    public Result<PageInfo<Question>> findAllQues(@PathVariable Integer pageNum) {
        PageInfo<Question>  questionPageInfo = questionService.findAllQues(pageNum);
        return new Result<PageInfo<Question>>(true, StatusCode.OK, "查询成功", questionPageInfo);
    }
    
    //分页查询所有专家
    @Operation(summary = "分页查询所有专家")
    @GetMapping("/findExpert/{pageNum}")
    public Result<PageInfo<Expert>> findPage(@PathVariable Integer pageNum) {
        PageInfo<Expert> expertPageInfo = expertService.findExpertPage(pageNum);
        return new Result<PageInfo<Expert>>(true, StatusCode.OK, "查询成功", expertPageInfo);
    }
    
    //分页条件查询专家
    @Operation(summary = "分页条件查询专家")
    @GetMapping("/findExpertByKeys/{keys}/{pageNum}")
        public Result<PageInfo<Expert>> findExpertByKeys(@PathVariable("keys") String keys,@PathVariable Integer pageNum) {
        PageInfo<Expert> expertPageInfo = expertService.findExpertByKeys(keys,pageNum);
        return new Result<PageInfo<Expert>>(true, StatusCode.OK, "查询成功", expertPageInfo);
    }

    //分页条件查询专家
    @Operation(summary = "分页条件查询专家")
    @GetMapping("/findExpertUser/{pageNum}")
    public Result<PageInfo<Expert>> findExpertUser(@PathVariable Integer pageNum) {
        PageInfo<Expert> ExpertUserPageInfo = expertService.findExpertPage(pageNum);
        return new Result<PageInfo<Expert>>(true, StatusCode.OK, "查询成功", ExpertUserPageInfo);
    }

    // 测试接口：直接查询用户问答记录（用于调试）
    @Operation(summary = "测试接口：直接查询用户问答记录")
    @GetMapping("/test/selectByQuestioner/{questioner}")
    public Result<List<Question>> testSelectByQuestioner(@PathVariable("questioner") String questioner) {
        System.out.println("=== 测试接口被调用 ===");
        System.out.println("查询用户: " + questioner);
        
        try {
            List<Question> questions = questionService.selectByQuestioner(questioner);
            System.out.println("查询结果: " + questions);
            return new Result<List<Question>>(true, StatusCode.OK, "测试查询成功", questions);
        } catch (Exception e) {
            System.out.println("查询异常: " + e.getMessage());
            e.printStackTrace();
            return new Result<List<Question>>(false, StatusCode.ERROR, "查询失败: " + e.getMessage(), null);
        }
    }

}